package user

import (
	"beegoProject17/models/auth"
	"beegoProject17/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strings"
)

type MyCenterController struct {
	beego.Controller
}

func (c *MyCenterController) Get() {

	id := c.GetSession("id")
	fmt.Println("MyCenterController-ID: ", id)

	// 数据库
	o := orm.NewOrm()
	user := auth.User{}

	qs := o.QueryTable("sys_user")
	qs.Filter("id", id).One(&user)

	c.Data["user"] = user
	c.TplName = "user/my-center-edit.html"

}

func (c *MyCenterController) Post() {

	// 通过前端等uid获取
	id, _ := c.GetInt("uid")
	username := c.GetString("username")
	oldPwd := c.GetString("old_pwd")
	newPwd := c.GetString("new_pwd")
	age, _ := c.GetInt("age")
	gender, _ := c.GetInt("gender")
	phone, _ := c.GetInt64("phone")
	addr := c.GetString("addr")
	addNew := strings.Trim(addr, " ")
	isActive, _ := c.GetInt("is_active")

	/*	fmt.Println("修改前用户信息: =============")
		fmt.Println("uid", id)
		fmt.Println("username", username)
		fmt.Println("ord_pwd", oldPwd)
		fmt.Println("new_pwd", newPwd)
		fmt.Println("age", age)
		fmt.Println("gender", gender)
		fmt.Println("phone", phone)
		fmt.Println("addr", addr)
		fmt.Println("is_active", isActive)*/

	/*
		密码对比
	*/
	o := orm.NewOrm()
	qs := o.QueryTable("sys_user")
	user := auth.User{}
	qs.Filter("id", id).One(&user)
	fmt.Println("user: ", user)

	// (由于md5加密是不可逆的，所以需要通过再次加密对比的方式)
	oldPwdMd5 := utils.Md5Text(oldPwd) // 将原密码转换md5

	// 前端
	messageMap := map[string]interface{}{}

	if oldPwdMd5 != user.Password {
		messageMap["code"] = 10001
		messageMap["msg"] = "原密码错误"
	} else {
		// 数据库更新
		qs.Filter("id", id).Update(orm.Params{
			// 更新数据赋值
			"username":  username,
			"password":  utils.Md5Text(newPwd),
			"age":       age,
			"Gender":    gender,
			"phone":     phone,
			"addr":      addNew,
			"is_active": isActive,
		})
		messageMap["code"] = 200
		messageMap["msg"] = "修改成功"
	}
	c.Data["json"] = messageMap
	c.ServeJSON()
}
